const cartAbout = {
  namespaced: true,
  // 没有网络请求可以越过actions
  mutations: {
    ADDTOCART(state, good) {
      // 判断购物车是否加入重复商品
      const findResult = state.cart.find(item => item.goods_id === good.goods_id)
      if (findResult) {
        findResult.goods_count++
      } else state.cart.push(good)
      // 存入本地——持久化
      this.commit('cartAbout/SAVETOLOCAL')
    },
    // 保存本地
    SAVETOLOCAL(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    // 修改选中状态
    CHANGESTATE(state, good) {
      const findResult = state.cart.find(item => item.goods_id === good.goods_id)
      if (findResult) {
        findResult.goods_state = !good.goods_state
        this.commit('cartAbout/SAVETOLOCAL')
      }
    },
    // 修改数量
    CHANGECOUNT(state, good) {
      const findResult = state.cart.find(item => item.goods_id === good.goods_id)
      if (findResult) {
        findResult.goods_count = good.goods_count
        this.commit('cartAbout/SAVETOLOCAL')
      }
    },
    // 删除商品
    DELETEGOOD(state, good) {
      state.cart = state.cart.filter(item => item.goods_id !== good.goods_id)
      this.commit('cartAbout/SAVETOLOCAL')
    },
    // 取消全选
    SELECTALLORNOT(state, newState) {
      state.cart.forEach(item => item.goods_state = newState)
      this.commit('cartAbout/SAVETOLOCAL')
    }
  },
  state: {
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  },
  getters: {
    // 购物车商品数量
    total(state) {
      let count = 0
      state.cart.forEach(good => count += good.goods_count)
      return count
    },
    // 勾选商品的数量
    checkedCount(state) {
      let count = 0
      state.cart.filter(item => item.goods_state).forEach(item => count += item.goods_count)
      return count
    },
    // 商品的结算价格
    GoodsAmountPrice(state) {
      let price = 0
      const newArr = state.cart.filter(item => item.goods_state).forEach(item => price += item.goods_price * item.goods_count)
      return price.toFixed(2)
    }
  }
}
export default cartAbout